import time
from collections import OrderedDict
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.models import inception_resnet_v2
BatchNorm2d = nn.BatchNorm2d

class PadTop(nn.Module):
    def __init__(self):
        super(PadTop, self).__init__()
    def forward(self, xs):
        xs = torch.cat([xs[:, :, 0:1, :], xs], dim=2)
        return xs


class ConvNormAct(nn.Module):
    def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=(0, 0), dilation=(1, 1), bias=False):
        super(ConvNormAct, self).__init__()
        self.conv = nn.Sequential(
            nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, padding=padding, stride=stride,
                      bias=bias,dilation=dilation),
            BatchNorm2d(out_channels, momentum=0.1),
            nn.ReLU(inplace=True)
        )
    def forward(self, x):
        x = self.conv(x)
        return x
class Mixed_Down(nn.Module):
    def __init__(self, in_ch):
        super(Mixed_Down, self).__init__()
        self.branch0 = ConvNormAct(in_ch, in_ch, kernel_size=3, stride=2, padding=1)
        self.branch1 = nn.Sequential(
            ConvNormAct(in_ch, in_ch//2, kernel_size=1, stride=1),
            ConvNormAct(in_ch//2, in_ch//2, kernel_size=3, stride=1, padding=1),
            ConvNormAct(in_ch//2, in_ch//2, kernel_size=3, stride=2, padding=1)
        )
        self.branch2 = nn.Sequential(
            ConvNormAct(in_ch, in_ch//2, kernel_size=1, stride=1),
            nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        )
    def forward(self, x):
        x0 = self.branch0(x)
        x1 = self.branch1(x)
        x2 = self.branch2(x)
        out = torch.cat((x0, x1, x2), 1)
        return out
class NormDown(nn.Module):
    def __init__(self, in_ch):
        super(NormDown, self).__init__()
        self.branch0 = ConvNormAct(in_ch, in_ch*2, kernel_size=3, stride=2, padding=1)

    def forward(self, x):
        x0 = self.branch0(x)
        return x0



class R2DliaBlock(nn.Module):
    expansion = 1
    def __init__(self, inplanes, planes, scale_factor=0):
        super(R2DliaBlock, self).__init__()
        self.relu = nn.ReLU(inplace=True)
        self.width = inplanes*scale_factor
        self.ip = self.width//4
        self.conv0 = ConvNormAct(inplanes, self.width, kernel_size=3, stride=1, padding=1)
        self.conv1 = ConvNormAct(self.ip, self.ip, kernel_size=1, padding=0)
        self.conv2 = ConvNormAct(self.ip, self.ip, kernel_size=3, padding=1)
        self.conv3 = ConvNormAct(self.ip, self.ip, kernel_size=3, padding=2, dilation=2)
        self.conv4 = ConvNormAct(self.ip, self.ip, kernel_size=3, padding=3, dilation=3)
        self.conv_out = nn.Sequential(
            nn.Conv2d(self.width, planes, kernel_size=1, stride=1, padding=0, bias=False),
            BatchNorm2d(planes),
        )
    def forward(self, x):
        residual = x
        out = self.conv0(x)
        x1, x2, x3, x4 = torch.split(out, self.ip, dim=1)
        x1 = self.conv1(x1)
        x2 = self.conv2(x1+x2)
        x3 = self.conv3(x2+x3)
        x4 = self.conv4(x3+x4)
        out = torch.cat([x1, x2, x3, x4], dim=1)
        out = self.conv_out(out)
        out += residual
        out = self.relu(out)
        return out
class CovBlock(nn.Module):
    expansion = 1
    def __init__(self, inplanes):
        super(CovBlock, self).__init__()
        self.conv1 = ConvNormAct(inplanes, inplanes, kernel_size=3, stride=1, padding=1)
        self.conv2 = nn.Conv2d(inplanes, inplanes, kernel_size=3, stride=1, padding=1, bias=False)
        self.bn2 = BatchNorm2d(inplanes , momentum=0.1)
        self.relu = nn.ReLU(inplace=True)
    def forward(self, x):
        residual = x
        out = self.conv1(x)
        out = self.conv2(out)
        out = self.bn2(out)
        out += residual
        out = self.relu(out)
        return out


class SegLayer(nn.Module):
    def __init__(self, is_pad=True):
        super(SegLayer, self).__init__()

        self.steam = ConvNormAct(3, 16, kernel_size=7, stride=2, padding=3)
        self.conv1 = nn.Sequential(
            ConvNormAct(16, 32, kernel_size=3, stride=2, padding=1),
            CovBlock(32),
            CovBlock(32)
        )
        self.down1 = NormDown(32)
        self.conv2 = nn.Sequential(
            CovBlock(64),
            CovBlock(64)
        )
        self.down2 = NormDown(64)
        self.conv3 = nn.Sequential(
            R2DliaBlock(128, 128,scale_factor=1),
            R2DliaBlock(128, 128,scale_factor=2),
            R2DliaBlock(128, 128,scale_factor=2),
            R2DliaBlock(128, 128,scale_factor=2),
        )
        self.down3 = NormDown(128)
        self.conv4 = nn.Sequential(
            R2DliaBlock(256, 256, scale_factor=1),
            R2DliaBlock(256, 256, scale_factor=1),
        )

    def forward(self, x):
        x1 = self.steam(x)
        x1 = self.conv1(x1)

        x2 = self.down1(x1)
        x2 = self.conv2(x2)

        x3 = self.down2(x2)
        x3 = self.conv3(x3)

        x4 = self.down3(x3)
        x4 = self.conv4(x4)

        return x1,x2,x3,x4


class DetailLayer(nn.Module):
    def __init__(self, is_pad=True):
        super(DetailLayer, self).__init__()

        self.steam = ConvNormAct(3, 64, kernel_size=3, stride=2, padding=1)
        self.conv1 = nn.Sequential(
            ConvNormAct(64, 64, kernel_size=3, stride=2, padding=1),
            ConvNormAct(64, 64, kernel_size=3, stride=1, padding=1),
            ConvNormAct(64, 64, kernel_size=3, stride=1, padding=1)
        )
        self.conv2 = nn.Sequential(
            ConvNormAct(64, 128, kernel_size=3, stride=2, padding=1),
            ConvNormAct(128, 128, kernel_size=3, stride=1, padding=1),
            ConvNormAct(128, 128, kernel_size=3, stride=1, padding=1)
        )

    def forward(self, x):
        x1 = self.steam(x)
        x1 = self.conv1(x1)
        x2 = self.conv2(x1)
        return x1, x2


class BGALayer(nn.Module):

    def __init__(self,d_ch, seg_ch):
        super(BGALayer, self).__init__()
        self.left1 = nn.Sequential(
            nn.Conv2d(d_ch, d_ch, kernel_size=3, stride=1,padding=1, groups=d_ch, bias=False),
            nn.BatchNorm2d(d_ch),
            nn.Conv2d(d_ch, d_ch, kernel_size=1, stride=1,padding=0, bias=False),
        )
        self.left2 = nn.Sequential(
            nn.Conv2d(d_ch, d_ch, kernel_size=3, stride=2,padding=1, bias=False),
            nn.BatchNorm2d(d_ch),
            nn.AvgPool2d(kernel_size=3, stride=2, padding=1, ceil_mode=False)
        )
        self.right1 = nn.Sequential(
            nn.Conv2d(seg_ch, d_ch, kernel_size=3, stride=1,padding=1, bias=False),
            nn.BatchNorm2d(d_ch),
        )
        self.right2 = nn.Sequential(
            nn.Conv2d(seg_ch, seg_ch, kernel_size=3, stride=1,padding=1, groups=seg_ch, bias=False),
            nn.BatchNorm2d(seg_ch),
            nn.Conv2d(seg_ch, d_ch, kernel_size=1, stride=1,padding=0, bias=False),
        )
        self.up1 = nn.Upsample(scale_factor=4)
        self.up2 = nn.Upsample(scale_factor=4)

        self.conv = nn.Sequential(
            nn.Conv2d(
                d_ch, d_ch, kernel_size=3, stride=1,
                padding=1, bias=False),
            nn.BatchNorm2d(d_ch),
            nn.ReLU(inplace=True), # not shown in paper
        )
    def forward(self, x_d, x_s):
        left1 = self.left1(x_d)
        left2 = self.left2(x_d)
        right1 = self.right1(x_s)
        right2 = self.right2(x_s)
        right1 = self.up1(right1)
        left = left1 * torch.sigmoid(right1)
        right = left2 * torch.sigmoid(right2)
        right = self.up2(right)
        out = self.conv(left + right)
        return out
class Segnet(nn.Module):
    def __init__(self, num_class):
        super(Segnet, self).__init__()
        self.num_class = num_class
        self.detail = DetailLayer()
        self.seg = SegLayer()
        self.bg1 = BGALayer(128, 256)
        self.bg2 = BGALayer(64, 128)
        self.mask_pred = nn.Conv2d(64+128, self.num_class, kernel_size=1, padding=0, bias=True)
    def forward(self, x):

        detail4, detail8 = self.detail(x)
        seg4, seg8, seg16, seg32 = self.seg(x)
        seg8 = self.bg1(detail8,seg32)
        seg4 = self.bg2(detail4,seg16)
        seg8 = F.interpolate(seg8, scale_factor=2, mode='bilinear', align_corners=False)
        seg4 = torch.cat([seg8, seg4], dim=1)
        seg4 = self.mask_pred(seg4)
        seg4 = F.interpolate(seg4, scale_factor=4, mode='bilinear', align_corners=False)
        return seg4


def resnet_xag_18(is_pad=True):
    model = Segnet(is_pad)
    return model



if __name__ == '__main__':
    md = resnet_xag_18()

    x = torch.randn(1,3, 544 ,960)
    for i in range(1000000):
        t = time.time()
        md(x)
        print(1/(time.time()-t))
